// 交易相关功能

function setupEventListeners() {
    // 价格类型切换
    const priceType = document.getElementById('price-type');
    if (priceType) {
        priceType.addEventListener('change', (e) => {
            const limitPriceGroup = document.getElementById('limit-price-group');
            if (limitPriceGroup) {
                limitPriceGroup.classList.toggle('hidden', e.target.value !== 'limit');
            }
        });
    }

    // 股票代码自动填充
    document.querySelectorAll('.trade-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const code = e.target.dataset.code;
            const stockCodeInput = document.getElementById('stock-code');
            if (stockCodeInput) {
                stockCodeInput.value = code;
            }
            
            // Switch to trade page
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active-nav');
            });
            const tradePageNavItem = document.querySelector('[data-target="trade-page"]');
            if (tradePageNavItem) {
                tradePageNavItem.classList.add('active-nav');
            }
            
            document.querySelectorAll('.page').forEach(page => {
                page.classList.remove('active');
            });
            const tradePage = document.getElementById('trade-page');
            if (tradePage) {
                tradePage.classList.add('active');
            }
        });
    });

    // 刷新按钮
    const refreshBtn = document.getElementById('refresh-btn');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', () => {
            renderStockTable();
        });
    }

    // 表单提交
    const tradeForm = document.getElementById('trade-form');
    if (tradeForm) {
        tradeForm.addEventListener('submit', (e) => {
            e.preventDefault();
            executeTrade();
        });
    }

    // 新建策略按钮
    const newStrategyBtn = document.getElementById('btn-new-strategy');
    if (newStrategyBtn) {
        newStrategyBtn.addEventListener('click', () => {
            alert('跳转到策略创建页面');
        });
    }
}

function executeTrade() {
    const code = document.getElementById('stock-code').value;
    const type = document.getElementById('trade-type').value;
    const priceType = document.getElementById('price-type').value;
    const amount = parseInt(document.getElementById('trade-amount').value);
    const limitPrice = parseFloat(document.getElementById('limit-price').value);

    if (!code || !amount) {
        alert('请填写完整交易信息');
        return;
    }

    const stock = mockStocks.find(s => s.code === code);
    if (!stock) {
        alert('未找到该股票');
        return;
    }

    const price = priceType === 'market' ? stock.price : limitPrice;

    if (type === 'buy') {
        // 买入逻辑
        const cost = price * amount;
        if (cost > account.balance) {
            alert('可用资金不足');
            return;
        }

        account.balance -= cost;
        const existingPos = account.positions.find(p => p.code === code);
        if (existingPos) {
            existingPos.amount += amount;
            existingPos.cost = ((existingPos.cost * existingPos.amount) + cost) / (existingPos.amount + amount);
        } else {
            account.positions.push({
                code,
                name: stock.name,
                amount,
                cost: price,
                buyDate: new Date().toISOString()
            });
        }
    } else {
        // 卖出逻辑
        const position = account.positions.find(p => p.code === code);
        if (!position || position.amount < amount) {
            alert('持仓不足');
            return;
        }

        account.balance += price * amount;
        position.amount -= amount;

        if (position.amount === 0) {
            account.positions = account.positions.filter(p => p.code !== code);
        }
    }

    updateAccountInfo();
    renderPortfolioTable();
    alert(`委托成功：${type === 'buy' ? '买入' : '卖出'} ${stock.name} ${amount}股`);
    document.getElementById('trade-form').reset();
}